<?php 
App::uses('AppController', 'Controller');
App::uses('Sanitize', 'Utility');
class SearchController extends AppController {
	
	public $components = array('Link', 'Strings');
	
	/**
	 * @author VuLee
	 */
	public function index($rootCatId = null, $catId = null) {
		
		// Load PostModel
		$this->loadModel("Post");
		// Load  RegionModel
		$this->loadModel("Region");
		// Load RootCategoryModel
		$this->loadModel('RootCategory');
		// Load RootCategoryModel
		$this->loadModel('Category');
		
		$root_category = ZERO;
		$category_id = ZERO;
		
		$searchCategory = POST_CATEGORY_ALL;
		if($rootCatId != null && $catId != null) {
			$searchCategory = $rootCatId . '_' . $catId;
			$searchCategory = $this->checkSearchCategory($searchCategory);
			if($searchCategory != POST_CATEGORY_ALL) {
				$root_category = $rootCatId;
				$category_id = $catId;
			}
		}
		
		
		
		// Get search text
		$searchText = '';
		$tempSearchText ="";
		if(!empty($this->request->query['searchText'])){
			$searchText = $this->request->query['searchText'];
			$tempSearchText = $this->Strings->replaceHTMLTag ($searchText);
			$tempSearchText = Sanitize::stripScripts($tempSearchText);
			$tempSearchText = Sanitize::stripTags($tempSearchText);
			$tempSearchText = Sanitize::escape($tempSearchText);
			if (strpos($tempSearchText, '%') !== false
					|| strpos($tempSearchText, '_') !== false) {
				$tempSearchText = ZERO.ZERO.ZERO;
			}
			// Add search text condition
			$conditions[] = array('title_en LIKE ' => '%' . $this->Link->vietnamese_permalink($tempSearchText, " ") . '%');
		}
		
		$tempSearchText = Sanitize::html($tempSearchText);
		$this->set("searchText", $tempSearchText);

		

		// Get search category
		//$searchCategory = POST_CATEGORY_ALL;
		if(!empty($this->request->query['searchCategory'])){
			$searchCategory = $this->request->query['searchCategory'];
			$searchCategory = $this->checkSearchCategory($searchCategory);
			if($searchCategory != POST_CATEGORY_ALL){
				$arr = explode("_", $searchCategory);
				
				//$root_category = $arr[0];
				$root_category = isset($arr[0]) ? (string)(int)$arr[0] : ZERO;
				
				//$category_id = $arr[1];
				$category_id = isset($arr[1]) ? (string)(int)$arr[1] : ZERO;
				
			}
		}

		// Add search category condition
		$conditions[] = array('category_ids LIKE ' => $searchCategory . '%');
		$this->set("root_category", $root_category);
		$this->set("category_id", $category_id);
		$this->set("searchCategory", $searchCategory);
		//title for layout search category
		if(!empty($category_id)){
			$categoryName = $this->Category->findById($category_id);
			$this->set('title_for_layout', $categoryName['Category']['category_name']);
		}else{
			$this->set('title_for_layout', "Tìm rao vặt");
		}

		// Get search region
		if (!empty($this->request->query['searchRegion'])) {
			$searchRegion = $this->request->query['searchRegion'];
			// Check search region valid, region only 65 item, 1 to 65
			if (intval($searchRegion) < 1 || intval($searchRegion) > POST_MAX_COUNT_REGION) {
				$searchRegion = ZERO;
			}

		}else{
			$searchRegion = ZERO;
		}

		// Add search region condition
		if($searchRegion != ZERO){
			$conditions[] = array('region_id' => $searchRegion);
		}
		$this->set("searchRegion", $searchRegion);

		$searchBuySell = POST_SELL;
		// Get search buy or sell
		if(!empty($this->request->query['searchBuySell'])){
			$searchBuySell = $this->request->query['searchBuySell'];
			
			$searchBuySell = isset($searchBuySell) ? (string)(int)$searchBuySell : POST_SELL;
			
			if ((intval($searchBuySell) != POST_SELL && intval($searchBuySell) != POST_BUY)) {
				// Default sell
				$searchBuySell = POST_SELL;
			}

		}
		// Add search buy or sell condition
		$conditions[] = array('buy_sell' => $searchBuySell);
		$this->set("searchBuySell", $searchBuySell);

		// Get search all, person or company
		$searchPersonCompany = ZERO;
		if (!empty($this->request->query['searchPersonCompany'])) {
			$searchPersonCompany = $this->request->query['searchPersonCompany'];
			$searchBuySell = isset($searchPersonCompany) ? (string)(int)$searchPersonCompany : ZERO;
			if (intval($searchPersonCompany) != POST_COMPANY && intval($searchPersonCompany) != POST_PERSON) {
				$searchPersonCompany = ZERO;
			}

		}

		// Add search region condition
		if($searchPersonCompany != ZERO){
			$conditions[] = array('person_company' => $searchPersonCompany);
		}
		// Add check_status on
		$conditions[] = array('check_status' => CHECKED_STATUS);

		$this->set("searchPersonCompany", $searchPersonCompany);

  		$this->paginate = array(
                                'limit' => ITEM_PER_PAGE,
                                'order' => array('Post.updated_at' => 'desc'),
                             );
      
        $data = $this->paginate("Post", $conditions);
        // Add time post column
        $data = $this->addTimePostColumn($data);
        $this->set("data", $data);

		// Get all regions
		$regionAll = $this->Region->findAllData();
		$this->set("regionAll", $regionAll);


        $categoryAll = $this->RootCategory->findAllData();
        $this->set("categoryAll", $categoryAll);

	}

	/**
	 * Check category correct
	 * @author VuLee
	 */
	private function checkSearchCategory($searchCategory){
		// Check search category equal  POST_CATEGORY_ALL
		if (empty($searchCategory)) return POST_CATEGORY_ALL;
		// Search text correct format: {root_categories}_{child_categories}
		$arr = explode("_", $searchCategory);
		if(count($arr) != 2) return POST_CATEGORY_ALL;

		$temp_root_categories = $arr[0];
		$temp_categories = $arr[1];
		// Check category is integer number and greater than 1
		if((intval($temp_root_categories) < 1) || (intval($temp_categories) < 1)) return POST_CATEGORY_ALL;

		// Load RootCategoryModel
		
		// Check {root_categories} existed
		$data = $this->RootCategory->findById($temp_root_categories);

		if(empty($data)) return POST_CATEGORY_ALL;

		$this->loadModel("Category");
		// Check {child_categories} and {root_categories} existed
		$data = $this->Category->findByCategoryIdAndRootCategoryId($temp_categories, $temp_root_categories);
		if(empty($data)) return POST_CATEGORY_ALL;
		
		return $searchCategory;
	}

	/**
	 * Add time post column for lists
	 *
	 * @author VuLee
	 */
	private function addTimePostColumn($data){
		for ($i=0; $i < count($data); $i++) { 
			$data[$i]['Post']['time_post'] = $this->calculateTimePost($data[$i]['Post']['updated_at']);
		}
		return $data;
	}

	/**
	 * Calculate time post
	 *
	 * @author VuLee
	 */
	private function calculateTimePost($old_date){
		date_default_timezone_set('Asia/Ho_Chi_Minh');
		$current_date = date('Y-m-d H:i:s');
		$old_date = date_create($old_date);

		$current_date = date_create($current_date);
		$diff = date_diff($old_date, $current_date);

		$year = $diff->y;
		if ($year > 0) {
			return $year." năm";
		}

		$month = $diff->m;
		if ($month > 0) {
			return $month." tháng";
		}

		$day = $diff->d;
		if ($day > 0) {
			return $day." ngày";
		}

		$hour = $diff->h;
		if ($hour > 0) {
			return $hour." giờ";
		}

		$minute = $diff->i;
		$hour = $diff->h;
		if ($minute > 0) {
			return $minute." phút";
		}
		return "Mới đây";
	}
}
?>